import { useGetState } from "ahooks";
import { Select, Switch } from "antd";
import { useEffect, useState } from "react";
import "./index.scss"

export type TablePaginationConf = {
  pageSize: number,
  showTotal: boolean,
  showQuickJumper: boolean,
  showSizeChanger: boolean
}
type TablePaginationSelectorType = {
  onChange?: Function,
  value?: false | TablePaginationConf
}
export const initTablePaginationConf = {
  pageSize: 10,
  showTotal: true,
  showQuickJumper: false,
  showSizeChanger: true
}
export function TablePaginationSelector(props: TablePaginationSelectorType){
  const {onChange,value} = props
  
  const [switchValue, setSwitchValue] = useState(value===false?false:true);
  
  const [pValue, setPValue, getPValue] = useGetState<TablePaginationConf>(initTablePaginationConf);

  useEffect(()=>{
    if(value){
      setPValue(value as unknown as TablePaginationConf)
    }
  },[])
  function backValue(state: boolean){
    if(state){
      onChange?.(pValue)
    }else{
      onChange?.(false)
    }
    setSwitchValue(state)
  }
  function changeTotal(showTotal: boolean){
    setPValue(pValue=>({...pValue,showTotal}))
    setTimeout(() => {
      onChange?.(getPValue())
    }, 100);
  }
  function changeJumper(showQuickJumper: boolean){
    setPValue(pValue=>({...pValue, showQuickJumper}))
    onChange?.({...pValue, showQuickJumper})
  }

  function changePageSize(pageSize: number){
    setPValue(pValue=>({...pValue, pageSize}))
    onChange?.({...pValue, pageSize})
  }
  function changeShowSizeChanger(showSizeChanger: boolean){
    setPValue(pValue=>({...pValue, showSizeChanger}))
    onChange?.({...pValue,showSizeChanger})
  }
 
  return (
    <>
      <Switch value={switchValue} onChange={backValue}/>
      {switchValue && (
        <div className="tablePaginationSelectorForm">
          <div>
            <span>显示总数</span>
            <Switch value={pValue.showTotal} onChange={changeTotal}/>
          </div>
          <div>
            <span>显示跳转</span>
            <Switch value={pValue.showQuickJumper} onChange={changeJumper}/>
          </div>
          <div>
            <span>改变数据条数</span>
            <Switch value={pValue.showSizeChanger} onChange={changeShowSizeChanger}/>
          </div>
          <div>
            <span>每页条数</span>
            <Select
              value={pValue.pageSize}
              size="small"
              onChange={changePageSize}
              options={[10, 20, 50, 100].map(cell=>({value: cell, label: cell}))}
            />
          </div>
        </div>
      )}
    </>
  )
}